//
//  APNS.m
//  Cycling
//
//  Created by chijianguo on 2023/4/23.
//

#import "APNS.h"

@implementation APNS

static APNS* volatile _sharedInstance = nil;
+ (APNS*) shareInstance {
    static dispatch_once_t __once = 0;
    dispatch_once(&__once, ^{ _sharedInstance = [[APNS alloc] init]; });
    return _sharedInstance;
}

- (id) init {
    self = [super init];
    if (self) {
        return self;
    }
    return self;
}

+ (void)regLocalAPNs {
    UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert categories:nil];
    [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
}

+ (void)regRemoteAPNs:(id) delegate {
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionCarPlay) completionHandler:^(BOOL granted, NSError *_Nullable error) {
        if (!error) {
            NSLog(@"request authorization succeeded!");
        }
    }];
    
    [[UIApplication sharedApplication] registerForRemoteNotifications];
    //设置通知的代理
    center.delegate = delegate;
}

+ (void)pushNotifacation:(NSString *)info {
    
    [self pushNotifacation:nil subtitle:nil body:info userInfo:nil afterDelay:0.1];
}



+ (void)pushNotifacation:(NSString *)title  subtitle:(NSString *)subtitle  body:(NSString *)body userInfo:(NSDictionary *)userInfo afterDelay:(NSTimeInterval)afterDelay
{
    //UNMutableNotificationContent 通知还需完善
//    if ([UIDevice currentDevice].systemVersion.floatValue >= 10.0){
//        [self creatLocalPushIOS10FromTitle:title subtitle:subtitle body:body userInfo:userInfo afterDelay:afterDelay];
//    }else{
        [self creatLocalPushFrom:title alertBody:body alertAction:nil userInfo:userInfo  afterDelay:afterDelay];
//    }
}

#pragma mark ----------------------- 创建本地推送 ios10之后 ------------------------
+ (void)creatLocalPushIOS10FromTitle:(NSString *)title  subtitle:(NSString *)subtitle  body:(NSString *)body userInfo:(NSDictionary *)userInfo  afterDelay:(NSTimeInterval)afterDelay
{
    // 创建本地通知也需要在appdelegate中心进行注册
    // 1.创建通知内容
    UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
    content.title = title;
    content.subtitle = subtitle;
    content.body = body;
    content.userInfo = userInfo;
    
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    NSNumber *badge = [NSNumber numberWithInteger:[UIApplication sharedApplication].applicationIconBadgeNumber] ;

    content.badge = badge;
    
//    NSError *error = nil;
    
//    // 2.设置通知附件内容
//    NSMutableDictionary *optionsDict = [NSMutableDictionary dictionary];
//    // 一个包含描述文件的类型统一类型标识符（UTI）一个NSString。如果不提供该键，附件的文件扩展名来确定其类型，常用的类型标识符有 kUTTypeImage,kUTTypeJPEG2000,kUTTypeTIFF,kUTTypePICT,kUTTypeGIF ,kUTTypePNG,kUTTypeQuickTimeImage等。
//
//    // 需要导入框架 #import<MobileCoreServices/MobileCoreServices.h>
//    optionsDict[UNNotificationAttachmentOptionsTypeHintKey] = (__bridge id _Nullable)(kUTTypeMovie);
//    // 是否隐藏缩略图
//    optionsDict[UNNotificationAttachmentOptionsThumbnailHiddenKey] = @YES;
//    // 剪切缩略图
//    optionsDict[UNNotificationAttachmentOptionsThumbnailClippingRectKey] = (__bridge id _Nullable)((CGRectCreateDictionaryRepresentation(CGRectMake(0.25, 0.25, 0.5 ,0.5))));
//    // 如果附件是影片，则以第几秒作为缩略图
//    optionsDict[UNNotificationAttachmentOptionsThumbnailTimeKey] = @1;
    
    //    NSLog(@"NSBundle = %@",[NSBundle mainBundle]);
    
//    // 添加附件
//    NSString *path = [[NSBundle mainBundle] pathForResource:@"WeChatSight1" ofType:@"mp4"];
//    //optionsDict如果不需要，可以不设置，直接传nil即可
//    UNNotificationAttachment *att = [UNNotificationAttachment attachmentWithIdentifier:@"TestRequestvideo" URL:[NSURL fileURLWithPath:path] options:optionsDict error:&error];
//    if (error)
//    {
//        NSLog(@"attachment error %@", error);
//    }
//    content.attachments = @[att];
//    content.launchImageName = @"imageName@2x";
    
    // 2.设置声音
    UNNotificationSound *sound = [UNNotificationSound defaultSound];
    content.sound = sound;
    // 3.触发模式 多久触发，是否重复
    // 3.1 按秒
    UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:afterDelay>0 ?afterDelay : 0.01 repeats:NO];
    
    // 4.设置UNNotificationRequest
    UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"Identifierdalay" content:content trigger:trigger];
    
    //5.把通知加到UNUserNotificationCenter, 到指定触发点会被触发
    [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
    }];
}

#pragma mark - 创建本地推送 ios 4-10
+ (void)creatLocalPushFrom:(NSString *)alertTitle  alertBody:(NSString *)alertBody   alertAction:(NSString *)alertAction userInfo:(NSDictionary *)userInfo afterDelay:(NSInteger)afterDelay
{
    // 1.创建通知
    UILocalNotification *localNotification = [[UILocalNotification alloc] init];
    // 2.设置通知的必选参数
    // 设置通知显示的内容
    localNotification.alertTitle = alertTitle;
    localNotification.alertBody = alertBody;
    // 设置通知的发送时间,单位秒，在多少秒之后推送
    localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:0];
    //解锁滑动时的事件
    localNotification.alertAction =alertAction;
    //收到通知时App icon的角标
    localNotification.applicationIconBadgeNumber = 0;
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    
    //推送是带的声音提醒，设置默认的字段为UILocalNotificationDefaultSoundName
    localNotification.soundName = UILocalNotificationDefaultSoundName;
    //设置推送自定义声音格式
    //localNotification.soundName = @"文件名.扩展名";
    //循环次数
    localNotification.repeatInterval = 0;//kCFCalendarUnitDay;
    // 3.发送通知(根据项目需要使用)
    // 方式一: 根据通知的发送时间(fireDate)发送通知
    [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
}

+ (void) locationPushNoti:(CLRegion *) region body:(NSString *)body {
    UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
    
    //空的推送，只有声音
    content.body = body;//region.identifier;
    content.title = @"Emojo app";
    //    content.categoryIdentifier = @"test";
    
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    NSNumber *badge = [NSNumber numberWithInteger:[UIApplication sharedApplication].applicationIconBadgeNumber] ;
    
    content.badge = badge;
    
    //    NSError *error = nil;
    // 2.设置通知附件内容
    NSMutableDictionary *optionsDict = [NSMutableDictionary dictionary];
    // 一个包含描述文件的类型统一类型标识符（UTI）一个NSString。如果不提供该键，附件的文件扩展名来确定其类型，常用的类型标识符有 kUTTypeImage,kUTTypeJPEG2000,kUTTypeTIFF,kUTTypePICT,kUTTypeGIF ,kUTTypePNG,kUTTypeQuickTimeImage等。
    
    // 需要导入框架 #import<MobileCoreServices/MobileCoreServices.h>
    optionsDict[UNNotificationAttachmentOptionsTypeHintKey] = (__bridge id _Nullable)(kUTTypeMovie);
    // 是否隐藏缩略图
    optionsDict[UNNotificationAttachmentOptionsThumbnailHiddenKey] = @YES;
    // 剪切缩略图
    optionsDict[UNNotificationAttachmentOptionsThumbnailClippingRectKey] = (__bridge id _Nullable)((CGRectCreateDictionaryRepresentation(CGRectMake(0.25, 0.25, 0.5 ,0.5))));
    // 如果附件是影片，则以第几秒作为缩略图
    optionsDict[UNNotificationAttachmentOptionsThumbnailTimeKey] = @1;
    
    
    // 2.设置声音
    UNNotificationSound *sound = [UNNotificationSound defaultSound];
    content.sound = sound;
    
    UNLocationNotificationTrigger* trigger = [UNLocationNotificationTrigger
                                              triggerWithRegion:region repeats:NO];
    
    // 4.设置UNNotificationRequest
    UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"Identifierdalay" content:content trigger:trigger];
    
    //5.把通知加到UNUserNotificationCenter, 到指定触发点会被触发
    [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
    }];
}


+ (void)deleteLocalPush {

    // 取消所有的本地推送
    [[UIApplication sharedApplication]  cancelAllLocalNotifications];
    
}

@end
